import html2canvas from 'html2canvas';
// import { loadSvgfile } from '@/utils/loadSvgFile'
export const captureAndDownloadSnapshot = async ( element : HTMLElement | null | undefined, filename : string ) => {
	try {
		if (!element) {
			ElMessage.warning('未找到要截图的元素');
            return; // 直接返回，避免后续操作
		}
        element.style.overflow = 'visible';
        // await loadSvgfile(element);
        const scale = window.devicePixelRatio || 1;
        const canvas = await html2canvas(element, {
            scale: scale,
            useCORS: true,
            logging: false, // 关闭日志输出
            allowTaint: false, // 避免污染画布    
            // onclone: (doc) => {
            //     // 设置 willReadFrequently 属性
            //     const ctx = doc.querySelector('canvas')?.getContext('2d');
            //     if (ctx) {
            //         ctx.canvas.willReadFrequently = true;
            //     }
            // }        
        });
        const dataUrl = canvas.toDataURL('image/png');
        downloadImage(dataUrl, filename);
		// // 捕捉快照				
	} catch (error) {
		console.error('Error capturing snapshot:', error);
	}
};
const downloadImage = (dataUrl:string,filename:string) => {
    const blob = dataURLToBlob(dataUrl);
    if (blob) {
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
};

const dataURLToBlob = (dataURL:string) => {
    const byteString = atob(dataURL.split(',')[1]);
    const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0;i < byteString.length;i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab],{ type:mimeString });
};